﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using HT.Future.Common;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace HT.Future.FileServer.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UserController : ControllerBase
    {


        [HttpPost]
        //public async Task<string> Index([FromBody] Tuple<string> tuple, [FromServices] IWebHostEnvironment host)
        public async Task<string> Index([FromBody] Dictionary<string, string> dic, [FromServices] IWebHostEnvironment host)
        //public async Task<string> Index([FromBody] JObject json, [FromServices] IWebHostEnvironment host)
        {
            //var data = json.GetValue("item1").Value<string>();
            var data = dic["item1"];
            var filename = Guid.NewGuid().ToString().ToLower().Replace("-", "") + ".jpg";
            var path = Path.Combine(host.WebRootPath, "faces", filename);
            UtilHelper.CreateDirectory(Path.GetDirectoryName(Path.Combine(host.WebRootPath, "faces")));
            using HttpClient client = new HttpClient();
            var img = await client.GetByteArrayAsync(data);
            using FileStream file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            file.Write(img, 0, img.Length);

            return filename;
        }
    }
}
